package com.cars.ui.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cars.dto.Customer;
import com.cars.service.LoginService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	LoginService loginService = null;

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();

		loginService = new LoginService();
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("login.jsp");

		request.setAttribute("errorMessageStatus", "hide");
		request.setAttribute("errorMessage",null);

		dispatcher.forward(request, response);

	
 	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		if ((userName != null && !userName.trim().equalsIgnoreCase(""))
				&& (password != null && !password.trim().equalsIgnoreCase("")))

		{

			Customer customer = loginService.loadCustomer(userName, password);

			if (customer != null) {

				request.getSession(true).setAttribute("customer", customer);
			 
				response.sendRedirect("index.jsp");

			} else {

				RequestDispatcher dispatcher = request
						.getRequestDispatcher("login.jsp");

				request.setAttribute("errorMessageStatus", "show");
				request.setAttribute("errorMessage",
						"Invalid User Name / Password , Please try again.");

				dispatcher.forward(request, response);

			}

		} else {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("login.jsp");

			request.setAttribute("errorMessageStatus", "show");
			request.setAttribute("errorMessage",
					"Please Enter Valid User Name / Password.");

			dispatcher.forward(request, response);

		}

	}
}
